package bag

import (
	"github.com/gogf/gf/v2/os/gctx"
	"github.com/gogf/gf/v2/os/glog"
	"xr-game-server/core/constants/cmd"
	"xr-game-server/core/constants/common"
	"xr-game-server/core/push"
	"xr-game-server/dao/bagdao"
	"xr-game-server/entity"
	"xr-game-server/module/protocol"
)

const (
	CellMax        = 2
	CellNum uint64 = 100
)

type BagHandler struct {
}

func initResHandler() {
	protocol.RegItemHandler(protocol.Bag, newBagHandler())
}

func (this *BagHandler) CanConsume(roleId uint64, model *protocol.ItemModel) bool {
	//TODO implement me
	caches := bagdao.GetBagCells(roleId)
	for _, cache := range caches {
		if cache.CfgId == model.Id {
			return cache.Val >= model.Val
		}
	}
	return false
}

func (this *BagHandler) Consume(roleId uint64, items []*protocol.ItemModel, canPush bool) bool {
	for _, item := range items {
		if !this.CanConsume(roleId, item) {
			return false
		}
	}
	for _, item := range items {
		cell := bagdao.GetBagCell(roleId, item.Id)
		item.TypeId = common.Subtract
		if cell == nil {
			glog.Infof(gctx.New(), "roleid=%v,消费背包数据异常itemId=%v", roleId, item.Id)
			return false
		}
		item.Old = cell.Val
		cell.Consume(item.Val)
		item.Current = cell.Val
	}
	if canPush {
		rets := make([]*entity.PlayerBag, common.Zero)

		for _, model := range items {
			db := bagdao.GetBagCell(roleId, model.Id)
			if db != nil {
				rets = append(rets, db)
			}
		}
		if len(rets) > common.Zero {
			push.Data(roleId, cmd.BagVal, newArrayCellDto(rets))
		}
	}
	return false
}
func (this *BagHandler) AddItem(roleId uint64, items []*protocol.ItemModel, canPush bool) {
	//空闲格子数量
	cacheData := bagdao.GetBagCells(roleId)
	//默认背包格子大小,此处可以根据实际项目调整
	cellSize := CellMax
	cellNum := CellNum
	currentSize := common.Zero
	for _, cache := range cacheData {
		if cache.Val > common.Zero {
			currentSize++
		}
	}

	for _, item := range items {
		cell := bagdao.GetBagCell(roleId, item.Id)
		item.TypeId = common.Add
		if cell == nil {
			//判断格子是否满了
			if currentSize+1 > cellSize {
				//无法加
				item.Fail = item.Val
				continue
			}
			newCell := entity.NewPlayerBag(roleId, item.Id)
			item.Old = newCell.Val
			success := newCell.Add(item.Val, cellNum)
			item.Current = newCell.Val
			item.Fail = item.Val - success
			//直接塞到缓存
			bagdao.AddToCache(roleId, newCell)
			currentSize++
		} else {
			//格子数量
			item.Old = cell.Val
			success := cell.Add(item.Val, cellNum)
			item.Current = cell.Val
			item.Fail = item.Val - success
		}
	}
	if canPush {
		rets := make([]*entity.PlayerBag, common.Zero)

		for _, model := range items {
			db := bagdao.GetBagCell(roleId, model.Id)
			if db != nil {
				rets = append(rets, db)
			}
		}
		if len(rets) > common.Zero {
			push.Data(roleId, cmd.BagVal, newArrayCellDto(rets))
		}
	}
	//判断背包是否满了
	for _, val := range items {
		if val.Fail > common.Zero {
			push.OutData(roleId, cmd.FullBag)
			return
		}
	}

}

func newBagHandler() protocol.ItemHandler {
	return &BagHandler{}
}
